<?php

namespace app\store\model\appointment;

use app\common\model\BaseModel;
use app\common\model\server\User as UserModel;
use app\store\service\order\Export1 as Exportservice;
use think\Db;

/**
 * 预约订单模型
 * Class BalanceLog
 * @package app\store\model\user
 */
class Service extends BaseModel
{
    protected $name = 'appointment_service';

    public function lists($user_id, $is_settled = -1, $start_time = null, $end_time = null, $search = null, $phone = null)
    {
        $where = [];

        if ($user_id > 0) $where['s.service_id'] = $user_id;
        if ($is_settled != '' && $is_settled > -1){
            $where['s.pay_status'] = $is_settled;
        }

        if($start_time != null){
            $start_time = strtotime($start_time);
        }else{
            $start_time = 0;
        }
        if($end_time != null){
            $end_time = strtotime($end_time) + 86400;
        }else{
            $end_time = time();
        }
        $where['s.end_time'] = ['between',[$start_time,$end_time]];
        if($search != null){
            $where['order.service_name'] = ['like','%'.$search.'%'];
        }
        if($phone != null){
            $where['order.user_phone|order.order_id'] = ['like','%'.$phone.'%'];
        }
        $pay_status = [0 => '未结算', 1 => '已结算'];
        $rec_status = [0 => '直派单', 1 => '转单'];
        return $this->alias('s')
            ->join('appointment_order order', 'order.id = s.order_id', 'left')
            ->join('appointment_type type', 'type.type_id = order.type_id', 'left')
            ->join('appointment_time time', 'time.time_id = order.time_id', 'left')
            //->join('comment', 'comment.order_id = order.id', 'left')
            ->join('server_user user', 'user.user_id = s.service_id', 'left')
            ->where([
                's.status' => 1,
                's.is_delete' => 0,
                's.wxapp_id' => self::$wxapp_id,/*comment.content,comment.score,*/
            ])->where($where)->field('order.stars,order.ping,order.order_id order_no,order.offline_from,order.offline_name,order.offline_remark,type.name type_name,order.appointment_date date,time.desc time_name,order.is_offline,order.is_rec,order.p_service_name,
             order.user_name,order.user_phone,order.address,user.real_name server_name,user.mobile server_phone,
             s.start_time,s.end_time,s.use_time,s.price,s.service_price,s.pay_status,order.id order_id,s.real_price,s.remark,order.service_id,order.user_goods_id,order.type_id,s.server_num')
            ->order('s.create_time desc')->
            paginate(15, false, [
                'query' => \request()->request()
            ])->each(function ($item, $key) use ($pay_status, $rec_status) {

                $item['date'] = date("Y-m-d", $item['date']);

                if ($item['use_time'] == 0) {
                    $timediff = intval($item['end_time']) - intval($item['start_time']);
                    $item['use_time'] = number_format($timediff / 60, 0, '.', '').'分钟';
                    $item['use_time'] = '/';
                }else{
                    $item['use_time'] =  $item['use_time'].'小时';
                }

                if(!$item['price']){
                    $item['price'] = 0;
                }
                $item['start_time'] = $item['start_time'] > 0 ? date("Y-m-d H:i", $item['start_time']) : '/';
                $item['end_time'] = $item['end_time'] > 0 ? date("Y-m-d H:i", $item['end_time']) : '/';

                $item['pay_status_name'] = $pay_status[$item['pay_status']];
                if(empty($item['is_rec'])){
                    $item['is_rec_text'] = '';
                }else{
                    $item['is_rec_text'] = $rec_status[$item['is_rec']];
                }
                $item['is_offline'] = $item['is_offline'] == 0 ? $item['is_offline'] = '线上订单' : '线下订单';
                /*if($item['score']){
                    switch ($item['score']){
                        case 10 :
                            $item['score_name'] = '好评';
                            break;
                        case 20:
                            $item['score_name'] = '中评';
                            break;
                        case 30:
                            $item['score_name'] = '差评';
                            break;
                        default:
                            $item['score_name'] = '暂无评论';
                            break;
                    }

                }else{
                    $item['score_name'] = '暂无评论';
                }*/

            });
    }

    /**
     * 服务人员入驻审核
     * @param $data
     * @return bool
     */
    public function edit($data)
    {

        $where = [
            'is_delete' => 0,
            'wxapp_id' => self::$wxapp_id,
        ];
        $info = $this->where('order_id', $data['order_id'])
            ->where($where)
            ->find();
        if (empty($info)) {
            $this->error = '预约订单不存在';
            return false;
        }

        if ($info['status'] == 0) {
            $this->error = '预约订单未完成';
            return false;
        }

        if ($info['pay_status'] == 1) {
            $this->error = '已支付，不要重复支付';
            return false;
        }

        if (!is_numeric($data['reward_money'])) $data['reward_money'] = 0;
        $commission = $data['service_money'] + $data['reward_money'];

//        if ($commission <= 0.01) {
//            $this->error = '服务金额不能小于0';
//            return false;
//        }

        $order = Order::get(['id'=>$info['order_id']]);

        if($order['is_rec'] == 1)
        {
            if (!isset($info['p_bili'])) {
                $info['p_bili'] = 0;
            }
//var_dump($commission);
//var_dump($data['p_bili']);
            if($commission == 0){
                $p_money = 0;
            }else{
                $p_money = $data['p_bili'];//$commission * ($data['p_bili'] / 100);
            }

            UserModel::grantMoney($order['p_service_id'], $p_money);
            $this->allowField(true)
                ->where('order_id', $data['order_id'])
                ->update([
                    'service_price' => $data['service_money'],
                    'reward_price' => 0,
                    'real_price' => $p_money,
                    'remark' => $data['remark'],
                    'pay_status' => 1,
                    'pay_time'=>time()
                ]);

            UserModel::grantMoney($order['service_id'], ($commission - $p_money));

        }else{
            $money = $commission;

            UserModel::grantMoney($info['service_id'], $money);
            $this->allowField(true)
                ->where('order_id', $data['order_id'])
                ->update([
                    'service_price' => $data['service_money'],
                    'reward_price' => $data['reward_money'],
                    'real_price' => $money,
                    'remark' => $data['remark'],
                    'pay_status' => 1,
                    'pay_time'=>time()
                ]);
        }

//        if ($data['service_money'] > $data['order_money']) {
//            $this->error = '服务金额不能大于订单金额';
//            return false;
//        }
        //YPP 被转单服务人员也显示订单
        $infos = $this->where('order_id', $data['order_id'])->find();
        $ao = Db::name('appointment_order')->where('id',$infos['order_id'])->find();
        if($ao['p_service_id']>0){
            Db::name('appointment_service')->insert([
                'order_id' => $infos['order_id'],
                'service_id' => $ao['service_id'],
                'confirm_time' => $infos['confirm_time'],
                'is_start' => $infos['is_start'],
                'start_time' => $infos['start_time'],
                'end_time' => $infos['end_time'],
                'use_time' => $infos['use_time'],
                'price' => $infos['price'],
                'service_price' => $infos['service_price'],
                'reward_price' => $data['reward_money'],
                'real_price' => abs($infos['service_price']-$infos['real_price']),
                'remark' => $infos['remark'],
                'status' => $infos['status'],
                'pay_status' => $infos['pay_status'],
                'is_delete' => $infos['is_delete'],
                'wxapp_id' => $infos['wxapp_id'],
                'create_time' => time(),
                'update_time' => 0,
                'pay_time' => $infos['pay_time'],
                'is_show' => $infos['is_show'],
                'server_num' => $infos['server_num'],
            ]);
        }





        return true;
    }

    /**
     * 订单导出
     * @param $dataType
     * @param $query
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportList($dataType, $query)
    {
        // 获取订单列表
        $list = $this->getListAll($dataType, $query)->toArray();
        // 导出csv文件
        return (new Exportservice)->orderList($list);
    }

    /**
     * 订单列表(全部)
     * @param $dataType
     * @param array $query
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getListAll($dataType, $query = [])
    {

        $user_id = $query['user_id'];
        $is_settled = $query['is_settled']?$query['is_settled']:-1;
        $start_time = $query['start_time'];
        $end_time = $query['end_time'];
        $search = $query['search'];
        $phone = $query['phone'];
        $where = [];
        if ($user_id > 0) $where['s.service_id'] = $user_id;
        if ($is_settled > -1){
            $where['s.pay_status'] = $is_settled;
        }
        if($start_time != null){
            $start_time = strtotime($start_time);
        }else{
            $start_time = 0;
        }
        if($end_time != null){
            $end_time = strtotime($end_time) + 86400;
        }else{
            $end_time = time();
        }
        $where['s.end_time'] = ['between',[$start_time,$end_time]];
        if($search != null){
            $where['order.service_name'] = ['like','%'.$search.'%'];
        }
        if($phone != null){
            $where['order.user_phone'] = ['like','%'.$phone.'%'];
        }
        $pay_status = [0 => '未结算', 1 => '已结算'];
        $rec_status = [0 => '直派单', 1 => '转单'];

        return $this->alias('s')
            ->join('appointment_order order', 'order.id = s.order_id', 'left')
            ->join('appointment_type type', 'type.type_id = order.type_id', 'left')
            ->join('appointment_time time', 'time.time_id = order.time_id', 'left')
            //->join('comment', 'comment.order_id = order.user_order_id', 'left')
            ->join('server_user user', 'user.user_id = order.service_id', 'left')
            ->where([
                's.status' => 1,
                's.is_delete' => 0,
                's.wxapp_id' => self::$wxapp_id,/*comment.content,comment.score,*/
            ])->where($where)->field('order.stars,order.ping,order.order_id order_no,order.offline_from,order.offline_name,order.offline_remark,type.name type_name,order.appointment_date date,time.desc time_name,order.is_offline,order.is_rec,order.p_service_name,
             order.user_name,order.user_phone,order.address,user.real_name server_name,user.mobile server_phone,
             s.start_time,s.end_time,s.use_time,s.price,s.service_price,s.pay_status,order.id order_id,s.real_price,s.remark,order.service_id,order.user_goods_id,order.type_id,s.server_num')
            ->order('s.create_time desc')->
            paginate(5000, false, [
                'query' => \request()->request()
            ])->each(function ($item, $key) use ($pay_status, $rec_status) {
                $item['date'] = date("Y-m-d", $item['date']);

                if ($item['use_time'] == 0) {
                    $timediff = intval($item['end_time']) - intval($item['start_time']);
                    $item['use_time'] = number_format($timediff / 60, 0, '.', '').'分钟';
                    $item['use_time'] = '/';
                }else{
                    $item['use_time'] =  $item['use_time'].'小时';
                }

                if(!$item['price']){
                    $item['price'] = 0;
                }
                $item['start_time'] = $item['start_time'] > 0 ? date("Y-m-d H:i", $item['start_time']) : '/';
                $item['end_time'] = $item['end_time'] > 0 ? date("Y-m-d H:i", $item['end_time']) : '/';

                $item['pay_status_name'] = $pay_status[$item['pay_status']];
                if(empty($item['is_rec'])){
                    $item['is_rec_text'] = '';
                }else{
                    $item['is_rec_text'] = $rec_status[$item['is_rec']];
                }
                $item['is_offline'] = $item['is_offline'] == 0 ? $item['is_offline'] = '线上订单' : '线下订单';
                /*if($item['score']){
                    switch ($item['score']){
                        case 10 :
                            $item['score_name'] = '好评';
                            break;
                        case 20:
                            $item['score_name'] = '中评';
                            break;
                        case 30:
                            $item['score_name'] = '差评';
                            break;
                        default:
                            $item['score_name'] = '暂无评论';
                            break;
                    }

                }else{
                    $item['score_name'] = '暂无评论';
                }*/

            });
    }
}